<?php
namespace app\admin\controller;

use think\Controller;
use app\common\model\Category;

class Categories extends Controller
{
    /**
     * 获取分类列表
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return json
     */
    public function list()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);

        $list = Category::page($page, $limit)->select();
        $count = Category::count();

        return json([
            'code' => 1,
            'data' => [
                'list' => $list,
                'total' => $count,
                'last_page' => ceil($count / $limit)
            ]
        ]);
    }

    /**
     * 添加分类
     * @param string $name 分类名称
     * @param int $parent_id 父级ID
     * @param int $sort 排序
     * @return json
     */
    public function add()
    {
        if (!$this->request->isPost()) {
            return json(['code' => 0, 'msg' => '非法请求']);
        }

        $data = $this->request->post();
        $validate = validate('Category');
        if (!$validate->scene('add')->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        if (Category::create($data)) {
            return json(['code' => 1, 'msg' => '添加成功']);
        }
        return json(['code' => 0, 'msg' => '添加失败']);
    }

    /**
     * 编辑分类
     * @param int $id 分类ID
     * @param string $name 分类名称
     * @param int $sort 排序
     * @return json
     */
    public function edit()
    {
        if (!$this->request->isPost()) {
            return json(['code' => 0, 'msg' => '非法请求']);
        }

        $data = $this->request->post();
        $validate = validate('Category');
        if (!$validate->scene('edit')->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        $category = Category::find($data['id']);
        if (!$category) {
            return json(['code' => 0, 'msg' => '分类不存在']);
        }

        if ($category->save($data)) {
            return json(['code' => 1, 'msg' => '编辑成功']);
        }
        return json(['code' => 0, 'msg' => '编辑失败']);
    }

    /**
     * 删除分类
     * @param int $id 分类ID
     * @return json
     */
    public function delete()
    {
        $id = input('id/d', 0);
        if (!$id) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }

        // 检查是否有子分类
        if (Category::where('parent_id', $id)->count() > 0) {
            return json(['code' => 0, 'msg' => '请先删除子分类']);
        }

        if (Category::destroy($id)) {
            return json(['code' => 1, 'msg' => '删除成功']);
        }
        return json(['code' => 0, 'msg' => '删除失败']);
    }
} 